package com.tuandai.commons.hbase;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * hbase 连接utils
 *
 * Created by chenpi on 2017/3/20.
 */
public class TdConnectionUtils {

    private static Logger log = LoggerFactory.getLogger(TdConnectionUtils.class);

    /**
     * 创建一个新连接
     * @param props 配置properties
     * @return
     * @throws IOException
     */
    public static Connection createNewConnection(Properties props) throws IOException {
        log.info("new connection");
        Configuration conf = HBaseConfiguration.create();
        for(Map.Entry<Object,Object> prop : props.entrySet()){
            String key = String.valueOf(prop.getKey());
            String value = String.valueOf(prop.getValue());
            if(StringUtils.isBlank(key))
                continue;
            if(StringUtils.isBlank(value))
                continue;
            conf.set(key,value);
        }
        return ConnectionFactory.createConnection(conf);
    }

    /**
     * 创建新连接
     * @param props 配置properties
     * @param hadoopUser hadoop user
     * @return
     */
    public static Connection createNewConnection(Properties props,String hadoopUser) throws IOException {
        System.setProperty(Constants.HADOOP_USER_NAME_KEY, hadoopUser);
        return createNewConnection(props);
    }

    /**
     * 获取table
     * @param connection 连接
     * @param tableName 表名
     * @return
     */
    public static Table getTable(Connection connection, String tableName) throws IOException {
        return connection.getTable(TableName.valueOf(tableName));
    }

}
